<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="25">
        <el-col :span="7">
          <el-input placeholder="请输入内容"
          v-model="queryinfo.query"
           clearable
           @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button></el-input
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="adddialogVisible = true">添加</el-button>
        </el-col>
      </el-row>
      <template>
        <el-table stripe :data="userList" style="width: 100%">
          <el-table-column type="index" width="50"> </el-table-column>
          <el-table-column prop="username" label="姓名" width="180">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="150">
          </el-table-column>
          <el-table-column prop="mobile" label="电话" width="150">
          </el-table-column>
          <el-table-column prop="role_name" label="身份" width="100">
          </el-table-column>
          <el-table-column label="状态" width="80">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" active-color="#13ce66" @change="userStateChange(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" @click="showUser(scope.row.id)"></el-button>
              <el-button type="danger" icon="el-icon-delete"  @click="deleteUser(scope.row.id)"></el-button>
              <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
                
              >
                <el-button type="warning" icon="el-icon-setting" @click="SetRole(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
       <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryinfo.pagenum"
      :page-sizes="[1, 2, 10, 20]"
      :page-size="queryinfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
  <el-dialog
  title="添加用户"
  :visible.sync="adddialogVisible"
  width="50%"
  @close='adddialogClose'
  >
  <el-form :model="addForm" :rules="addFormrules" ref="addFormruleForm" label-width="70px" class="demo-ruleForm">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input v-model="addForm.password"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
    <el-form-item label="手机" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="adddialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="修改用户信息"
  :visible.sync="dialogVisible"
  width="50%"
  @close='editClose'
  >
  <el-form :model="editForm" :rules="editFormrules" ref="editFormruleForm" label-width="70px" class="demo-ruleForm">
    <el-form-item label="用户名" >
    <el-input  v-model="editForm.username"
  :disabled="true">
</el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
    <el-input v-model="editForm.email"></el-input>
  </el-form-item>
    <el-form-item label="手机" prop="mobile">
    <el-input v-model="editForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editformUserInfo">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="分配角色"
  :visible.sync="RoledialogVisible"
  width="50%"
  @close="SetRoleClose">
  <div>
    <p>用户姓名：{{userInfo.username}}</p>
    <p>现有角色：{{userInfo.role_name}}</p>
    <p>选择角色
      <el-select v-model="selectRole" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
    </p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="RoledialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRole()">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      total: 0,
      adddialogVisible:false,
      dialogVisible:false,
      addForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      RoledialogVisible:false,
      userInfo:{},
      rolesList:[],
       selectRole:{},
      editFormrules:{
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] } 
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/, message: "请输入合法手机号/电话号", trigger: "blur" }
        ],
      },
      editForm:{},
      addFormrules:{
         username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 100 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 15个字符", trigger: "blur" },
        ],
         email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] } 
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/, message: "请输入合法手机号/电话号", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      var { data: resp } = await this.$http.get("users", {
        params: this.queryinfo,
      });
      this.userList = resp.data.users;
      this.total = resp.data.total;
    },
     handleSizeChange(val) {
        this.queryinfo.pagesize = val
        this.getUserList()
      },
      handleCurrentChange(val) {
        this.queryinfo.pagenum =val
        this.getUserList()
      },
     async userStateChange(userinfo){
         await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      },
      adddialogClose(){
        this.$refs.addFormruleForm.resetFields()
      },
      editClose(){
        this.$refs.editFormruleForm.resetFields()
      },
      addUser(){
         this.$refs.addFormruleForm.validate(async val =>{
           if(!val) return
         var {data:resp} =await this.$http.post('users',this.addForm)
          this.adddialogVisible=false,
          this.getUserList()
         })
      },
     async showUser(id){
         this.dialogVisible=true;
        var {data:resp} =await this.$http.get('users/' + id)
        this.editForm =resp.data  
      },
      editformUserInfo(){
          this.$refs.editFormruleForm.validate(async val =>{
          var {data:resp} =await this.$http.put('users/'+ this.editForm.id,{email:this.editForm.email,mobile:this.editForm.mobile
           
          })
          // console.log(resp)
          this.dialogVisible=false;
          this.$message({
            showClose: true,
            message: "更新数据成功",
            type: "success",
          });
          })
      },
       async SetRole(userinfo){
        this.userInfo=userinfo
        var {data:resp} =await this.$http.get('roles')
        this.rolesList =resp.data
        this.RoledialogVisible=true;
      },
      async deleteUser(id){
        var con=  await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        })  .catch(err => err)       
         if (con !=='confirm') {
           return this.$message({
            type: 'info',
            message: '已取消删除'
          });
           
         }else{
           var {data:resp} = await this.$http.delete('users/'+id);
          this.$message({
            type: 'success',
            message: '删除成功!'
            });
         }
        },
          async  saveRole(){
          if (!this.selectRole) {
            return this.$message.error('请选择要分配的角色')
          }
           var {data:resp} = await this.$http.put(`users/${this.userInfo.id}/role`,
          {rid:this.selectRole}
          )
          this.$message.success('更新角色成功')
          this.getUserList()
          this.RoledialogVisible = false;
        },
        SetRoleClose(){
          this.selectRole=''
          this.userInfo={}
        }
      
  }
};
</script>

<style lang="less" scoped>
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2) !important;
}</style
